package com.yugao.fintech.antelope.mps.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.antelope.base.model.BasePlusPO;
import com.yugao.fintech.antelope.mps.mapper.MsgReceiverMapper;
import com.yugao.fintech.antelope.mps.mapper.ReceiverSubscribeMapper;
import com.yugao.fintech.antelope.mps.model.entity.MsgReceiver;
import com.yugao.fintech.antelope.mps.model.entity.ReceiverSubscribe;
import com.yugao.fintech.framework.assistant.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接收者订阅的推送 仓储层
 */
@Slf4j
@Repository
public class ReceiverSubscribeManager extends ServiceImpl<ReceiverSubscribeMapper, ReceiverSubscribe> implements IService<ReceiverSubscribe> {
    @Autowired
    private MsgReceiverMapper msgReceiverMapper;

    public List<MsgReceiver> listTaskSubscriber(Long taskId) {
        // 一般指定的任务接收人不会太多, 所以这里直接采用in语法
        LambdaQueryWrapper<ReceiverSubscribe> lqw = ReceiverSubscribe.lqw().eq(ReceiverSubscribe::getTaskId, taskId);
        List<Long> receiverIds = this.list(lqw).stream().map(ReceiverSubscribe::getReceiverId).distinct()
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(receiverIds)) {
            return Collections.emptyList();
        }

        LambdaQueryWrapper<MsgReceiver> receiverLqw = MsgReceiver.lqw().in(MsgReceiver::getId, receiverIds)
                .orderByDesc(BasePlusPO::getCreatedAt);
        return msgReceiverMapper.selectList(receiverLqw);
    }
}
